import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig, AxiosRequestConfig } from "axios";
import { message } from 'antd';
import { LocalStorageService } from '../utils/storage';

const instance: AxiosInstance = axios.create({
  baseURL: "https://test.gewu.juyuel.com:10010",
  timeout: 5000,
});

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = LocalStorageService.get("token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  return Promise.reject(error)
})

instance.interceptors.response.use((response: AxiosResponse) => {
  return response.data
}, (error) => {
  return Promise.reject(error)
})

/**
 * @description: 
 * @param {AxiosRequestConfig} config
 * @return {Promise}
 */
function request<T = any>(config: AxiosRequestConfig<T>): Promise<T> {
  return new Promise((resolve, reject) => {
    instance.request<any, T>(config).then((res: any) => {
      if (res.code !== 200 && res.code !== 'OK') {
        message.error(res.message)
        return reject(res)
      }
      resolve(res.data)
    }).catch((err) => {
      return reject(err)
    })
  })
}

export function get<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
  return request<T>({ ...config, method: 'GET', url })
}

export function post<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
  return request<T>({ ...config, method: 'POST', url })
}

export function put<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
  return request<T>({ ...config, method: 'PUT', url })
}

export function del<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
  return request<T>({ ...config, method: 'Delete', url })
}

export default instance